package com.lzh.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.commonutils.CommonResult;
import com.lzh.edu.client.VodClient;
import com.lzh.edu.entity.Video;
import com.lzh.edu.mapper.VideoMapper;
import com.lzh.edu.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.edu.vo.VideoInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author lizuhu
 * @since 2021-04-24
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VodClient vodClient;
    @Override
    public Boolean removeVideoByCourseId(String id) {
        //根据课程id查询课程所有的视频id
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", id);
        queryWrapper.select("video_source_id");
        List<Video> videoList = baseMapper.selectList(queryWrapper);
        //调用远程服务批量删除视频,但是需要注意的是，我们远程服务需要的String类型的参数，而当前我们查询到的是对象集合，所以需要转换
        ArrayList<String> videoIds = new ArrayList<>();
        for (int i = 0; i < videoList.size(); i++) {
            Video video = videoList.get(i);
            String videoSourceId = video.getVideoSourceId();
            videoIds.add(videoSourceId);
        }
        vodClient.removeBatchVideo(videoIds);
        Integer count = baseMapper.delete(queryWrapper);
        return null != count && count > 0;
    }

    @Override
    public Boolean removeVideoByVideoId(String videoId) {
        //根据小节id查询视频id
        Video video = baseMapper.selectById(videoId);
        String videoSourceId = video.getVideoSourceId();
        //删除视频资源
        if(!StringUtils.isEmpty(videoSourceId)){
            CommonResult result = vodClient.removeVideo(videoSourceId);
            if (result.getCode() !=200) {
                System.out.println("视频删除失败！熔断器！");
            }
        }
        Integer result = baseMapper.deleteById(videoId);
        return result != null && result > 0;
    }
}
